
import { globalUtils } from '../../common/js/global-utils/global-utils-all';
import uiData from 'ui-data';
import $ from 'jquery';

/* SOURCE-CODE-START */

"use strict";

$(function () {
  var jqForm = $('form');
  var jqCaptcha = $('#captchaImage');
  var model = uiData.model(jqForm[0]);

  // 刷新验证码
  refreshCaptcha();

  // 点击验证码刷新
  jqCaptcha.on('click', function () {
    refreshCaptcha();
  });

  // 点击登录按钮认证
  $('#loginBtn').on('click', function () {
    var data = model.getData('*');

    // 调用后端接口
    var deferred = $.ajax({
      url: 'doLogin',
      type: 'POST',
      data: data
    });

    // 调用接口成功后处理
    deferred.done(function (result, textStatus, jqXHR) {
      if (result.success) {
        var currentUrl = location.href;
        var backUrl;

        var index = currentUrl.indexOf('?backUrl=');
        if (index >= 0) {
          backUrl = currentUrl.substring(index + 9);
          backUrl = decodeURIComponent(backUrl);
        }

        if (globalUtils.isNullOrUndefined(backUrl) || !backUrl.startsWith('/')) {
          location.href = globalUtils.getFullUrl('/');
        } else {
          location.href = backUrl;
        }
      } else {
        var message = result.message;
        showAlert('warning', (message || '${t("ui.system.common.msg.unknownError")}'));

        // 刷新验证码
        refreshCaptcha();
      }
    });

    // 调用接口失败后处理
    deferred.fail(function (jqXHR, textStatus, errorThrown) {
      showAlert('danger', '${t("ui.account.login.msg.loginApiError")}');
    });
  });


  /**
   * 刷新验证码
   */
  function refreshCaptcha() {
    $.ajax({
      url: 'api/account/login/captcha',
      type: 'POST'
    }).done(function (result, textStatus, jqXHR) {
      if (result.success) {
        var captchaInfo = result.data;

        if (captchaInfo.captchaEnabled) {
          $('#captchaGroup').removeClass('d-none');

          model.setData(['captchaKey'], {
            captchaKey: captchaInfo.captchaKey
          });

          $('#captchaImage').attr('src', captchaInfo.captchaData);
        }
      } else {
        showAlert('warning', (message || '${t("ui.account.login.msg.failedToObtaincaptcha")}'));
      }
    });
  }

  /**
   * 显示警告框
   * @param {string} type 
   * @param {string} message 
   */
  function showAlert(type, message) {
    var format = '<div class="alert alert-{0} login-alert" role="alert">{1}</div>';
    var html = globalUtils.formatString(format, type, message);
    var jqElement = $(html).prependTo('body');

    jqElement.delay(1000).fadeOut('fast', function () {
      jqElement.remove();
    });
  }

});

/* SOURCE-CODE-END */
